<template>
  <center>
    <h1>进入实验模块</h1>
    <div>
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="ruleForm">
        <el-form-item label="用户名" prop="user">
          <el-input type="username" v-model="ruleForm.user" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="pass">
          <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户类别" prop="class">
          <el-radio v-model="ruleForm.class" label="2">独立PI</el-radio>
          <el-radio v-model="ruleForm.class" label="3">科研助理</el-radio>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
        </el-form-item>
      </el-form>
    </div>
  </center>
</template>

<script>

import {ElMessage} from "element-plus";
import {get} from "@/utils/http";

export default {
  name: "enterLab",
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        callback();
      }
    };

    const validateUser = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入用户名'));
      } else {
        callback();
      }
    };

    const validateClass = (rule, value, callback) => {
      if (value === 0) {
        callback(new Error('请选择用户类别'));
      } else {
        callback();
      }
    };

    return {
      ruleForm: {
        user: '',
        pass: '',
        class: 0,
      },
      rules: {
        user: [
          {validator: validateUser, trigger: 'blur'}
        ],
        pass: [
          {validator: validatePass, trigger: 'blur'}
        ],
        class: [
          {validator: validateClass, trigger: 'blur'}
        ]
      }
    };
  },
  created() {
    this.exp_id = this.$route.params.exp_id;
    this.pro_id = this.$route.params.pro_id;
    this.pro_name = this.$route.params.pro_name;
    if (this.exp_id === undefined){
      this.exp_id = sessionStorage.getItem("exp_id");
    }
    else {
      sessionStorage.setItem("exp_id",this.exp_id)
    }
    if (this.pro_id === undefined){
      this.pro_id = sessionStorage.getItem("pro_id");
    }
    else {
      sessionStorage.setItem("pro_id",this.pro_id)
    }
    if (this.pro_name === undefined){
      this.pro_name = sessionStorage.getItem("pro_name");
    }
    else {
      sessionStorage.setItem("pro_name",this.pro_name)
    }
  },
  methods: {
    submitForm(formName) {
      let that = this;
      let auth = true;
      Date.prototype.format = function(fmt){
        var o = {
          "M+" : this.getMonth()+1,                 //月份
          "d+" : this.getDate(),                    //日
          "h+" : this.getHours(),                   //小时
          "m+" : this.getMinutes(),                 //分
          "s+" : this.getSeconds(),                 //秒
          "q+" : Math.floor((this.getMonth()+3)/3), //季度
          "S"  : this.getMilliseconds()             //毫秒
        };

        if(/(y+)/.test(fmt)){
          fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
        }

        for(var k in o){
          if(new RegExp("("+ k +")").test(fmt)){
            fmt = fmt.replace(
                RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
          }
        }

        return fmt;
      }
      var now = new Date();
      var nowStr = now.format("yyyy-MM-dd hh:mm:ss");
      that.$refs[formName].validate((valid) => {
        if (valid) {
          get('/login', {
            username: that.ruleForm.user,
            password: that.ruleForm.pass
          }).then(function (res){
            if(res.code === 0){
              ElMessage.warning({
                showClose: true,
                message: "用户名或密码错误",
                type: "warning",
                center: true
              })
              return;
            }
            else{
              let class_role_mapper = {"checker": 1, "PI": 2, "assistant": 3, "logger": 4};
              if(class_role_mapper[res.data.role] != that.ruleForm.class){
                ElMessage.warning({
                  showClose: true,
                  message: "身份类型不匹配，请仔细核验！",
                  type: "warning",
                  center: true
                })
                return;
              }
              if(that.ruleForm.class == 2){
                console.log(that.exp_id);
                console.log(that.pro_id);
                get('/proPartialInfo/judge_authorization', {
                  exp_id: that.exp_id,
                  pro_id: that.pro_id,
                  pi_id: res.data.uid.toString(),
                  cur_time: nowStr
                }).then(function (aut){
                  if(aut.code == 0){
                    auth = false;
                    ElMessage.warning({
                      showClose: true,
                      message: "您在当前时间没有进入该功能单元的权限！",
                      type: "warning",
                      center: true
                    })

                  }
                });
              }
              setTimeout(function(){
              if(auth === true){
                let router_target;
                get('/loginLabLog/record', {
                  uid: res.data.uid,
                  username: that.ruleForm.user,
                  role: res.data.role,
                  loginlab_time: nowStr
                }).then(function (ans){
                  console.log(ans);
                })

                if (that.ruleForm.class==1){
                  router_target = "doCheck";
                }
                else if (that.ruleForm.class==2) {
                  router_target = "doLab";
                }
                else if (that.ruleForm.class==3) {
                  router_target = "doAssist";
                }
                else if (that.ruleForm.class==4) {
                  router_target = "doLog";
                }
                that.$router.push({
                  name: router_target,
                  params: {
                    exp_id: that.exp_id,
                    pro_id: that.pro_id,
                    pro_name: that.pro_name,
                    pi_id: res.data.uid.toString(),
                  }
                })
                ElMessage.success({
                  showClose: true,
                  message: "登陆成功，欢迎您 "+ that.ruleForm.user,
                  type: "success",
                  center: true
                })}},1000);

            }
          })


        } else {
          return false;
        }
      });
    },

  }
}

</script>

<style scoped>

.ruleForm {
  margin-top: 100px;
  width: max-content;
}
</style>